#define _CRT_SECURE_NO_WARNINGS 1
class Solution {
public:
    int minOperations(vector<int>& nums1, vector<int>& nums2) {
        int len1 = nums1.size();
        int len2 = nums2.size();
        vector<int> t1 = nums1;
        vector<int> t2 = nums2;
        int max1 = 0;
        int max2 = 0;
        for (int i = 0; i < len1; i++) {
            max1 = max(nums1[i], max1);
            max2 = max(nums2[i], max2);
        }

        if (max1 == nums1[len1 - 1] && max2 == nums2[len2 - 1])return 0;
        // if((max1!=nums[len1-1]&&max2!=nums2[len2-1]&&(max1>nums2[len2-1]||max2>nums1[len1-1]))return -1;
        int cnt1 = 0;
        max1 = 0;
        max2 = 0;
        for (int i = 0; i < len1; i++) {
            if ((t1[i] > t1[len1 - 1] && t2[i] <= t1[len1 - 1]) || (t2[i] > t2[len1 - 1] && t1[i] <= t2[len1 - 1])) {
                swap(t1[i], t2[i]);
                // max1=max(t2[i],max1);
                cnt1++;
            }
            else if ((t1[i] > t1[len1 - 1] && t2[i] > t1[len1 - 1]) || (t2[i] > t2[len1 - 1] && t1[i] > t2[len1 - 1])) {
                cnt1 = 0;
            }
            max1 = max(max1, t1[i]);
            max2 = max(max2, t2[i]);
        }
        if (cnt1 == 0 || (t1[len1 - 1] != max1 || t2[len1 - 1] != max2)) {
            cnt1 = 1e9;
        }
        int cnt2 = 1;

        swap(nums1[len1 - 1], nums2[len1 - 1]);
        t1 = nums1;
        t2 = nums2;
        max1 = 0;
        max2 = 0;
        for (int i = 0; i < len1; i++) {
            if ((t1[i] > t1[len1 - 1] && t2[i] <= t1[len1 - 1]) || (t2[i] > t2[len1 - 1] && t1[i] <= t2[len1 - 1])) {
                swap(t1[i], t2[i]);
                // max1=max(t2[i],max1);
                cnt2++;
            }
            else if ((t1[i] > t1[len1 - 1] && t2[i] > t1[len1 - 1]) || (t2[i] > t2[len1 - 1] && t1[i] > t2[len1 - 1])) {
                cnt2 = 0;
            }
            max1 = max(max1, t1[i]);
            max2 = max(max2, t2[i]);
        }
        if (cnt2 == 0 || (t1[len1 - 1] != max1 || t2[len1 - 1] != max2)) {
            cnt2 = 1e9;
        }
        if (cnt1 == 1e9 && cnt2 == 1e9)return -1;
        return min(cnt1, cnt2);

    }
};